/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.userorder.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.api.VO.IndexVO;
import com.jeeplus.modules.api.common.UUIDUtils;
import com.jeeplus.modules.api.enums.OrderStateEnum;
import com.jeeplus.modules.api.utils.WxAppPayUtils;
import com.jeeplus.modules.earnings.entity.Earnings;
import com.jeeplus.modules.earnings.service.EarningsService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.redeemcode.entity.RedeemCode;
import com.jeeplus.modules.redeemcode.service.RedeemCodeService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tickettype.entity.TicketType;
import com.jeeplus.modules.topic.entity.Topic;
import com.jeeplus.modules.topic.entity.TopicTicket;
import com.jeeplus.modules.topic.mapper.TopicTicketMapper;
import com.jeeplus.modules.topic.service.TopicService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.userorder.entity.UserOrder;
import com.jeeplus.modules.userorder.mapper.UserOrderMapper;

/**
 * 用户订单Service
 * @author zhych
 * @version 2021-08-23
 */
@Service
@Transactional(readOnly = true)
public class UserOrderService extends CrudService<UserOrderMapper, UserOrder> {

	@Autowired
	private UserOrderMapper userOrderMapper;

	@Autowired
	private RedeemCodeService redeemCodeService;

	@Autowired
	private TopicTicketMapper topicTicketMapper;

	@Autowired
	private TopicService topicService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private EarningsService earningsService;

	public UserOrder get(String id) {
		return super.get(id);
	}
	
	public List<UserOrder> findList(UserOrder userOrder) {
		return super.findList(userOrder);
	}
	
	public Page<UserOrder> findPage(Page<UserOrder> page, UserOrder userOrder) {
		return super.findPage(page, userOrder);
	}
	
	@Transactional(readOnly = false)
	public void save(UserOrder userOrder) {
		super.save(userOrder);
	}
	
	@Transactional(readOnly = false)
	public void delete(UserOrder userOrder) {
		super.delete(userOrder);
	}

	// 兑票
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void redeemOrder(UserOrder userOrder, RedeemCode code, Topic topic)  {
		// 修改兑换码的状态为已使用
		code.setRedeemState("1");
		code.setU(userOrder.getU());
		code.setOrderId(userOrder.getId());
		redeemCodeService.save(code);
		// 门票的销量加1
		RedeemCode redeemCode = redeemCodeService.get(code);
		Object o = topicTicketMapper.executeGetSql("select id from t_topic_ticket where topic_id = '" + userOrder.getTopic().getId() + "' and ticket_type_id = '" + redeemCode.getTicketTypeId() + "'");
		TopicTicket topicTicket = topicTicketMapper.get(o.toString());
		topicTicket.setSalesVolue(topicTicket.getSalesVolue() + userOrder.getQuantity());
		topicTicket.setStock(topicTicket.getStock() - userOrder.getQuantity());
		topicTicket.setSurplus(topicTicket.getSurplus() - userOrder.getQuantity());
		topicTicketMapper.update(topicTicket);
		// 主题的销量加1
		topic.setSalesValue(topic.getSalesValue() + userOrder.getQuantity());
		topic.setVirtualSalesValue(topic.getVirtualSalesValue() + userOrder.getQuantity());
		topicService.save(topic);
		super.save(userOrder);
	}

	// 创建订单
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void createOrder(UserOrder order, TopicTicket topicTicket) {
		// 保存订单
		super.save(order);
		// 主题门票添加销量
		topicTicket.setSalesVolue(topicTicket.getSalesVolue() + order.getQuantity());
		// 减库存
		topicTicket.setStock(topicTicket.getStock() + order.getQuantity());
		topicTicketMapper.update(topicTicket);
	}

	// 核销订单
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void verifyTicket(UserOrder order) {
		// 修改订单状态
		order.setOrderState(OrderStateEnum.FINISHED.getCode());
		order.setFinishDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		super.save(order);
	}

	// 支付回调
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void orderNotify(UserOrder order) {
		// 修改订单状态
		order.setOrderState(OrderStateEnum.WAIT_USE.getCode());
		order.setPayState("1");
		order.setPayDate(new Date());
		// 主题的销量加
		Topic topic = topicService.get(order.getTopic());
		topic.setSalesValue(topic.getSalesValue() + order.getQuantity());
		topic.setVirtualSalesValue(topic.getVirtualSalesValue() + order.getQuantity());
		topicService.save(topic);
		// 票种数量变更
		TopicTicket topicTicket = new TopicTicket();
		topicTicket.setTopic(order.getTopic());
		topicTicket.setTicketType(new TicketType(order.getTicketTypeId()));
		List<TopicTicket> list = topicTicketMapper.findList(topicTicket);
		if (CollectionUtils.isNotEmpty(list)) {
			TopicTicket topicTicket1 = list.get(0);
			// 销量加1
			topicTicket1.setSalesVolue(topicTicket1.getSalesVolue() + 1);
			topicTicketMapper.update(topicTicket1);
		}
		// 添加收益
		// 查询用户是否有推荐人
		Member member = memberService.get(order.getU());
		order.setBrokerage("0.00");
		order.setIncome(order.getPayAmount());
		if (!Objects.isNull(member.getInvite())) {
			// 查询推荐人
			Member invite = memberService.get(member.getInvite());
			// 根据比例添加收益
			if (!Objects.isNull(invite) && StringUtils.isNotBlank(invite.getRadio()) && new BigDecimal(invite.getRadio()).compareTo(BigDecimal.ZERO) > 0) {
				BigDecimal divide = new BigDecimal(invite.getRadio()).setScale(2, BigDecimal.ROUND_HALF_UP);
				Earnings earnings = new Earnings();
				earnings.setIsNewRecord(true);
				earnings.setId(UUIDUtils.orderUuid(6));
				earnings.setOrderId(order.getId());
				earnings.setPayment(order.getPayAmount());
				earnings.setU(invite);
				earnings.setRatio(invite.getRadio());
				earnings.setEarnings((new BigDecimal(order.getPayAmount()).multiply(divide)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
				earnings.setEarningsType("1");
				earningsService.save(earnings);
				order.setBrokerage((new BigDecimal(order.getPayAmount()).multiply(divide)).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
				order.setIncome((new BigDecimal(order.getPayAmount()).subtract((new BigDecimal(order.getPayAmount()).multiply(divide)))).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
			}
		}
		super.save(order);
	}

	/**
	 * 退款
	 * @param order 订单
	 * @param appId appId
	 * @param mchNo 商户号
	 * @param mchSecret 秘钥
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public Map<String, String> refund(UserOrder order, String appId, String mchNo, String mchSecret, String certPath) {
		JSONObject jsonObject = WxAppPayUtils.refundAppNew(order.getId(), order.getPayOrderId(), order.getPayAmount(), order.getPayAmount(), appId, mchNo, mchSecret, certPath);
		Map<String, String> map = new HashMap<>();
		if (!Objects.isNull(jsonObject)) {
			Map<String, String> params = JSONObject.parseObject(jsonObject.toJSONString(), new TypeReference<Map<String, String>>(){});
			if (params.get("msg").equals("success") && params.get("status").equals("success")) {
				logger.info("退款成功");
				map.put("k", "0");
				map.put("v", "退款成功");
				// 修改申请状态
				// 查询订单是否产生收益
				Earnings earnings = new Earnings();
				earnings.setOrderId(order.getId());
				earnings.setEarningsType("1");
				List<Earnings> list = earningsService.findList(earnings);
				if (CollectionUtils.isNotEmpty(list)) {
					Earnings earnings1 = list.get(0);
					Earnings earn = new Earnings();
					earn.setIsNewRecord(true);
					earn.setId(UUIDUtils.orderUuid(4));
					earn.setU(earnings1.getU());
					earn.setOrderId(order.getId());
					earn.setPayment(order.getPayAmount());
					earn.setEarningsType("3");
					earn.setEarnings(earnings1.getEarnings());
					earn.setRatio(earnings1.getRatio());
					earningsService.save(earn);
				}
				// 修改订单的状态
				order.setOrderState(OrderStateEnum.REFUNDED.getCode());
				order.setRefundDate(new Date());
				order.setCreateBy(UserUtils.getUser());
				order.setRefundMoney(order.getPayAmount());
				super.save(order);
			} else {
				logger.info(params.get("msg"));
				map.put("k", "1");
				map.put("v", params.get("msg"));
			}
		}
		return map;
	}
	@Transactional(readOnly = false)
	public List<IndexVO> week() {
		return userOrderMapper.week();
	}

	@Transactional(readOnly = false)
	public List<IndexVO> month() {
		return userOrderMapper.month();
	}

	@Transactional(readOnly = false)
	public List<IndexVO> year() {
		return userOrderMapper.year();
	}
}